﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ESBasic.ObjectManagement;
using ESPlus.Application.Chat.Passive;
using ESBasic.Emit.DynamicBridge;
using ESPlus.Application.Basic.Passive;
using ESFDemo.Forms;
using ESBasic.ObjectManagement.Forms;
using ESBasic;
using ESPlus.Application.Chat;
using ESFramework.Engine.Tcp.Passive;
using ESPlus.Rapid;
using ESPlus.Application.CustomizeInfo.Passive;
using ESFramework.Engine.ContractStyle.Stream;

namespace ESFDemo
{
    public partial class MainForm : Form, IBasicBusinessHandler, ICustomizeInfoBusinessHandler
    {
        private IBasicOutter basicOutter;
        private RapidPassiveEngine rapidPassiveEngine;
        private FormManager<string, ChatForm> chatFormManager = new FormManager<string, ChatForm>();    
        
        #region UserID
        private string userID;
        public string UserID
        {
            get { return userID; }
            set { userID = value; }
        } 
        #endregion

        public MainForm()
        {
            InitializeComponent();            
        }

        public void Initialize(string currentUserID, RapidPassiveEngine engine)
        {
            this.userID = currentUserID;
            this.rapidPassiveEngine = engine;
            this.basicOutter = engine.BasicOutter;

            this.rapidPassiveEngine.TcpPassiveEngine.ConnectionInterrupted += new CbGeneric(tcpPassiveEngine_ConnectionInterrupted);
            this.rapidPassiveEngine.TcpPassiveEngine.ConnectionRebuildFailure += new CbGeneric(tcpPassiveEngine_ConnectionRebuildFailure);
            this.rapidPassiveEngine.TcpPassiveEngine.ConnectionRebuildStart += new CbGeneric(tcpPassiveEngine_ConnectionRebuildStart);
            this.rapidPassiveEngine.TcpPassiveEngine.ConnectionRebuildSucceed += new CbGeneric(tcpPassiveEngine_ConnectionRebuildSucceed);

            this.toolStripLabel_loginfo.Text = string.Format("当前登录：{0}", currentUserID);
            this.toolStripLabel_state.Text = "连接状态：正常";

            this.InitializeFriends();            
        }

        private void InitializeFriends()
        {
            List<string> list = this.basicOutter.GetAllOnlineUsers();
            foreach (string friendID in list)
            {
                if (friendID != this.userID)
                {
                    this.listView1.Items.Add(friendID, 0);
                }
            }
        }

        private void OnDisconnected()
        {
            this.listView1.Clear();

            foreach (ChatForm form in this.chatFormManager.GetAllForms())
            {
                form.SelfOrFriendOffline();
            }
        }

        void tcpPassiveEngine_ConnectionRebuildSucceed()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbSimple(this.tcpPassiveEngine_ConnectionRebuildSucceed), null);
            }
            else
            {
                this.toolStripLabel_state.Text = "连接状态：正常（重连成功）";
                this.toolStripLabel_state.ForeColor = Color.Black;

                this.InitializeFriends();
            }
        }

        void tcpPassiveEngine_ConnectionRebuildStart()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbSimple(this.tcpPassiveEngine_ConnectionRebuildStart), null);
            }
            else
            {
                this.toolStripLabel_state.Text = "连接状态：断开，重连中......";
                this.toolStripLabel_state.ForeColor = Color.Red;
            }
        }

        void tcpPassiveEngine_ConnectionRebuildFailure()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbSimple(this.tcpPassiveEngine_ConnectionRebuildFailure), null);
            }
            else
            {
                this.toolStripLabel_state.Text = "连接状态：断开，重连失败";
                this.toolStripLabel_state.ForeColor = Color.Red;
            }
        }

        void tcpPassiveEngine_ConnectionInterrupted()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbSimple(this.tcpPassiveEngine_ConnectionInterrupted), null);
            }
            else
            {
                this.OnDisconnected();
                this.toolStripLabel_state.Text = "连接状态：断开";
                this.toolStripLabel_state.ForeColor = Color.Red;              
            }
        }

        void listView1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            if (e.Button != System.Windows.Forms.MouseButtons.Left)
            {
                return;
            }

            ListViewHitTestInfo info = this.listView1.HitTest(e.Location);
            if (info.Item != null)
            {
                ChatForm form = this.chatFormManager.GetForm(info.Item.Text);
                if (form == null)
                {
                    form = new ChatForm(this.userID, info.Item.Text, this.rapidPassiveEngine.CustomizeInfoOutter);
                    this.chatFormManager.Add(info.Item.Text, form);
                    form.Show();
                }

                form.Focus();
            }
        }

        #region IBasicBusinessHandler 成员

        public void OnFriendConnected(string friendID)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbGeneric<string>(this.OnFriendConnected), friendID);
            }
            else
            {
                this.listView1.Items.Add(friendID, 0);
            }
        }

        public void OnFriendOffline(string friendID)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbGeneric<string>(this.OnFriendOffline), friendID);
            }
            else
            {
                ListViewItem target = null;
                foreach (ListViewItem item in this.listView1.Items)
                {
                    if (item.Text == friendID)
                    {
                        target = item;
                        break;
                    }
                }

                if (target != null)
                {
                    this.listView1.Items.Remove(target);
                }

                ChatForm form = this.chatFormManager.GetForm(friendID);
                if (form != null)
                {
                    form.SelfOrFriendOffline();
                }
            }
        }

        public void OnBeingPushedOut()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbGeneric(this.OnBeingPushedOut), null);
            }
            else
            {
                this.OnDisconnected();
                this.toolStripLabel_state.Text = "连接状态：断开。在别处登录！" ;
                this.toolStripLabel_state.ForeColor = Color.Red;
                
            }
        }

        public void OnTimeoutOffline()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbGeneric(this.OnTimeoutOffline), null);
            }
            else
            {
                this.OnDisconnected();
                this.toolStripLabel_state.Text = "连接状态：心跳超时掉线！";
                this.toolStripLabel_state.ForeColor = Color.Red;               
            }
        }

        public void OnHaveLogonNotify()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbGeneric(this.OnHaveLogonNotify), null);
            }
            else
            {
                this.OnDisconnected();
                MessageBox.Show("该账号已经登录！");
            }
        }

        public void OnBeingKickedOut()
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbGeneric(this.OnBeingKickedOut), null);
            }
            else
            {
                this.OnDisconnected();
                this.toolStripLabel_state.Text = "连接状态：断开！";
                this.toolStripLabel_state.ForeColor = Color.Red;     
                MessageBox.Show("您已经被提出！");
            }
        }

        public void HandleBroadcast(string broadcasterID, string msg)
        {
            
        }

        public void HandleBroadcastFromServer(string msg)
        {
            
        }
        #endregion


        #region ICustomizeInfoBusinessHandler 成员      

        public void HandleBroadcast(string broadcasterID, string groupID, int informationType, byte[] info)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbGeneric<string,string, int, byte[]>(this.HandleBroadcast), broadcasterID,groupID, informationType, info);
            }
            else
            {
                if(broadcasterID != userID)
                {
                    ChatForm form = this.chatFormManager.GetForm(broadcasterID);
                    if (form == null)
                    {
                        form = new ChatForm(this.userID, broadcasterID, this.rapidPassiveEngine.CustomizeInfoOutter);
                        this.chatFormManager.Add(broadcasterID, form);
                        form.Show();
                    }

                    form.Focus();

                    TextChatContract contract = (TextChatContract)ESBasic.Helpers.SerializeHelper.DeserializeBytes(info, 0, info.Length);
                    form.ShowOtherTextChat(broadcasterID, contract);
                }
            }
        }

        public void HandleBroadcast(string broadcasterID, string groupID, int informationType, string info)
        {
            
        }

        public void HandleBroadcastFromServer(string groupID, int informationType, byte[] info)
        {
            
        }

        public void HandleBroadcastFromServer(string groupID, int informationType, string info)
        {
            
        }

        public void HandleInformation(string sourceUserID, int informationType, byte[] info)
        {
            if (this.InvokeRequired)
            {
                this.Invoke(new CbGeneric<string,int, byte[]>(this.HandleInformation), sourceUserID,informationType, info);
            }
            else
            {

                ChatForm form = this.chatFormManager.GetForm(sourceUserID);
                if (form == null)
                {
                    form = new ChatForm(this.userID, sourceUserID, this.rapidPassiveEngine.CustomizeInfoOutter);
                    this.chatFormManager.Add(sourceUserID, form);
                    form.Show();
                }

                form.Focus();

                TextChatContract contract = (TextChatContract)ESBasic.Helpers.SerializeHelper.DeserializeBytes(info, 0, info.Length);
                form.ShowOtherTextChat(sourceUserID, contract);
            }
        }

        public void HandleInformation(string sourceUserID, int informationType, string info)
        {
            
        }

        public void HandleInformationFromServer(int informationType, byte[] info)
        {
            
        }

        public void HandleInformationFromServer(int informationType, string info)
        {
            
        }

        #endregion      
    }
}
